//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager
-(void)requestWithType:(RequestType)type urlString:(NSString *)urlString patDic:(NSDictionary *)parDic finish:(RequestFinish)finish Error:(RequestError)error
{//拿到参数之后进行请求
    NSURL *url =[NSURL URLWithString:urlString];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //如果请求方式失败POST需要设置参数和请求方式
    if (type==POST) {
        //设置请求方式
        [request setHTTPMethod:@"POST"];
        //设置请求参数的Body
        //把字典转化为NSData类型的函数
        if (parDic.count>0) {
            NSData *data=[self parDicToDataWithDic:parDic];
              [request setHTTPBody:data];
        }
      
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }
        else
        {
            error(connectionError);
        }
    }];
    
}
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlString patDic:(NSDictionary *)parDic finish:(RequestFinish)finish Error:(RequestError)error
{
    PKRequestManager *pkRequestManager =[[PKRequestManager alloc]init ];
[pkRequestManager  requestWithType:type urlString:urlString patDic:parDic finish:finish Error:error];
    
    
}

-(NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array =[NSMutableArray arrayWithCapacity:0];
    //遍历字典得到每一个键，得到所有的key=Value类型的字符串
    for (NSString *key in dic) {
        NSString *string=[NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:string];
    }
    //数组里所有的Key =Value的字符串通过&符号链接
  NSString *parString =  [array componentsJoinedByString:@"&"];
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
